<?php
/**
 * Created by Alan.
 * User: Alan
 * Date: 2018\10\4 0004
 * Time: 14:05
 */

namespace app\admin\controller;


use app\admin\validate\CategoryValidate;
use app\common\model\Category as CategryModel;
use think\Controller;

class Category extends Controller
{
    //分类列表
    public function index()
    {
        $parentId = input('param.parent_id',0,'intval');
        $categories = CategryModel::getFirstCategorys($parentId);
        return $this->fetch('index',[
            'categories' => $categories
        ]);
    }

    //添加分类页
    public function add()
    {
        $categories = CategryModel::getNormalFirstCategory();
        return $this->fetch('add',[
            'categories' => $categories
        ]);
    }
    //编辑页
    public function edit($id=0)
    {
        if(intval($id) < 1){
            $this->error('参数不合法');
        }
        $category = CategryModel::get($id);
        $categorys = CategryModel::getFirstCategorys();
        return $this->fetch('edit',[
            'categorys' => $categorys,
            'category' => $category
        ]);
    }

    //添加或更新分类数据
    public function save()
    {
        if(!request()->isPost()){
            $this->error('请求失败');
        }

        $validate = (new CategoryValidate())->goCheck();
        if($validate!==true){
            $this->error($validate);
        }

        $data = [
            'name' => htmlentities(input('post.name','')),
            'id' => intval(input('post.id',0)),
            'parent_id' => input('post.parent_id')
        ];

        $res = (new CategryModel())->addOrUpdate($data);

        if($res){
            $this->success('新增或更新成功');
        }
        else {
            $this->error('新增或更新失败');
        }
    }

    //修改状态
    public function status()
    {
        $validate = (new CategoryValidate())->goCheck('status');
        if($validate!==true){
            $this->error($validate);
        }

        $categoryModel = new CategryModel();
        $res = $categoryModel->changeStatus(input('get.'));
        if($res){
//            $this->success('状态更新成功',null,'',1);
            $this->redirect($_SERVER['HTTP_REFERER']);
        }
        else{
            $this->error('状态更新失败');
        }

    }

    //分类排序
    public function listorder()
    {
        $val_msg = (new CategoryValidate())->goCheck('listorder');
        if($val_msg !== true){
            $this->result([],0,$val_msg);
        }

        $data = input('post.');
        $categoryModel = new CategryModel();
        $res = $categoryModel->changeListOrder($data);

        if($res){
            $this->result($_SERVER['HTTP_REFERER'],1,'success');
        }
        else {
            $this->result($_SERVER['HTTP_REFERER'],0,'更新失败');
        }
    }
}